#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" By Martin Senande-Rivera
    For Towards and atmosphere more favourable to firestorm development in Europe """

import os
import glob, sys
import numpy as np
import xarray as xr
import pandas as pd

path_fwi='../0-DATA/FWI/'
path_outs='./ERA5/'

# Read files
fwis=sorted(glob.glob(path_fwi+'ERA5_*.nc'))
FWI = xr.open_mfdataset(fwis,combine='by_coords')['fwi']

FWI = FWI.sel(time=slice('1979-01-01','2019-12-31'))

FWI_90 = FWI.resample(time='1Y',skipna=True).quantile(0.90, dim='time') # FWI daily 90th percentile
FWI_mean = FWI_90.mean(dim='time',skipna=True)                          # FWI 90th percentile time average
FWI_thres = 11.2                                                        # FWI minimum threshold
FWI_mean = xr.where(FWI_mean<FWI_thres,FWI_thres,FWI_mean)              # Where FWI 90th percentile is below FWI minimum threshold, 11.2 is the threshold
FWI_mean.to_netcdf(path_outs+'FWI_90threshold.nc')                      # Save output



